Decorator Pattern 1


In [1]:
def mean(first, second, *rest):
    """평균값 반환 함수"""
    numbers = (first, second) + rest
    return sum(numbers) / len(numbers)
  • Tip. 튜플 결합

In [2]:
(1, 2) + (3,)


Out[2]:
(1, 2, 3)

Decorator: 특정함수, 클래스, 메서드를 유일한 인자로 받음.


In [3]:
def float_args_and_return(function):
    def wrapper(*args, **kwargs):
        args = [float(arg) for arg in args]
        return float(function(*args, **kwargs))
    return wrapper

In [4]:
wrap_mean = float_args_and_return(mean)
  • 중첩된 decorator
    @decorator3
    @decorator2
    @decorator1
    [function, method, class]
    
    적용순서: [[[[function, method, class] -> @decorator1] -> @decorator2] -> @decorator3]

원본 함수의 속성값 소실문제


In [5]:
print(mean.__name__)
print(mean.__doc__)


mean
평균값 반환 함수

In [9]:
print(wrap_mean.__name__)
print(wrap_mean.__doc__)


wrapper
None

In [6]:
import functools

In [7]:
def float_args_and_return(function):
    @functools.wraps(function)  # __name__, __doc__ 승계, 디버깅에 유리
    def wrapper(*args, **kwargs):
        args = [float(arg) for arg in args]
        return float(function(*args, **kwargs))
    return wrapper

In [8]:
wrap_mean = float_args_and_return(mean)
print(wrap_mean.__name__)
print(wrap_mean.__doc__)


mean
평균값 반환 함수